import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns

# 生成虚拟数据集
np.random.seed(42)
data = {
    'feature1': np.random.choice(['A', 'B', 'C'], 100),
    'feature2': np.random.normal(50, 15, 100),
    'feature3': np.random.normal(30, 5, 100)
}
df = pd.DataFrame(data)

# 人为加入缺失值
missing_indices = np.random.choice(df.index, size=20, replace=False)
df.loc[missing_indices, 'feature1'] = np.nan

# 填补前的可视化
plt.figure(figsize=(15, 10))
plt.subplot(2, 2, 1)
sns.histplot(df['feature1'].dropna(), color='skyblue', kde=False)
plt.title('Missing Data - Feature1 Histogram')

plt.subplot(2, 2, 2)
sns.boxplot(x=df['feature1'].dropna(), y=df['feature2'], palette='Set2')
plt.title('Missing Data - Feature2 Boxplot by Feature1')

# 众数填补
mode_value = df['feature1'].mode()[0]
df['feature1'].fillna(mode_value, inplace=True)

# 填补后的可视化
plt.subplot(2, 2, 3)
sns.histplot(df['feature1'], color='coral', kde=False)
plt.title('Imputed Data - Feature1 Histogram')

plt.subplot(2, 2, 4)
sns.scatterplot(x=df['feature3'], y=df['feature2'], hue=df['feature1'], palette='viridis')
plt.title('Imputed Data - Feature2 vs Feature3 Scatter')

plt.tight_layout()
plt.show()